﻿using UnityEngine;
using System.IO;
using System;

namespace ZCTouchDrawBoard
{
    /// <summary>
    /// 透明纹理
    /// </summary>
    [Serializable]
    public class AlphaPaperView : BasePaperView
    {
        #region PublicMethod
        public override void Initialize(int width, int height, int depth = 16)
        {
            base.Initialize(width, height, depth, RenderTextureFormat.ARGB32, 1);
        }

        public override void Clear()
        {
            // 清除为透明纹理
            Use();
            GL.Clear(true, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
        }
        #endregion

        #region PublicMethod
        // 保存成PNG
        public void SaveToPng(string dir, string filename)
        {
            Use();
            // 创建一个屏幕大小的纹理，RGB24 位格（24位格没有透明通道，32位的有）
            Texture2D curTexture = new Texture2D(m_Width, m_Height, TextureFormat.ARGB32, false);
            // 读取屏幕内容到我们自定义的纹理图片中
            curTexture.ReadPixels(new Rect(0, 0, m_Width, m_Height), 0, 0);
            // 保存前面对纹理的修改
            curTexture.Apply();
            // 计算最后保存的图片大小
            Vector4 rect = new Vector4(99999f, 99999f, 0f, 0f);
            Color32[] colors = curTexture.GetPixels32();
            for (int i = 0; i < m_Width; i++)
            {
                for (int j = 0; j < m_Height; j++)
                {
                    if (colors[j * m_Width + i].a != 0)
                    {
                        rect.x = Mathf.Min(rect.x, i);
                        rect.y = Mathf.Min(rect.y, j);
                        rect.z = Mathf.Max(rect.z, i);
                        rect.w = Mathf.Max(rect.w, j);
                    }
                }
            }
            // 如果大小为0, 则什么都不做
            if (rect == new Vector4(99999f, 99999f, 0f, 0f))
            {
                return;
            }
            // 生成图片
            int minX = Mathf.CeilToInt(rect.x);
            int minY = Mathf.CeilToInt(rect.y);
            int maxX = Mathf.CeilToInt(rect.z);
            int maxY = Mathf.CeilToInt(rect.w);
            int width = maxX - minX;
            int height = maxY - minY;
            Color32[] resultImage = new Color32[width * height];
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    resultImage[j * width + i] = colors[(j + minY) * m_Width + (i + minX)];
                }
            }
            curTexture.Resize(width, height);
            curTexture.SetPixels32(resultImage);
            // 编码纹理为PNG格式
            byte[] bytes = curTexture.EncodeToPNG();
            // 销毁图片纹理
            Texture2D.Destroy(curTexture);
            // 将字节保存成图片，这个路径只能在PC端对图片进行读写操作
            File.WriteAllBytes(dir + filename + ".png", bytes);
        }
        #endregion
    }
}
